package com.csap.framework.oauth2;

import com.csap.framework.annotation.apidoc.ApiModel;
import com.csap.framework.annotation.apidoc.ApiModelProperty;
import com.csap.framework.util.map.CsapMap;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.SneakyThrows;

import java.lang.reflect.Field;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * 用户信息
 *
 * @author yangchengfu
 * @dataTime 2021年-07月-26日 00:07:00
 **/
@Data
@AllArgsConstructor
@NoArgsConstructor
@Builder
@ApiModel(description = "授权返回的用户信息", value = "用户信息")
public class UserInfo {
    @ApiModelProperty(description = "用户名", value = "用户名", forceRep = true)
    private String userName;
    @ApiModelProperty(description = "邮箱", value = "邮箱", forceRep = true)
    private String email;
    @ApiModelProperty(description = "昵称", value = "昵称", forceRep = true)
    private String nickName;
    @ApiModelProperty(description = "头像", value = "头像", forceRep = true)
    private String avatar;
    @ApiModelProperty(description = "手机号码", value = "手机号码", forceRep = true)
    private String mobile;
    @ApiModelProperty(description = "性别", value = "性别", forceRep = true)
    private Integer sex;
    @ApiModelProperty(description = "年龄", value = "年龄", forceRep = true)
    private Integer age;
    @ApiModelProperty(description = "用户属性", value = "用户属性", forceRep = true)
    private Map<String, List<String>> userAttribute;
    @ApiModelProperty(description = "用户角色", value = "用户角色", forceRep = true)
    private List<String> roleList;
    @ApiModelProperty(description = "用户角色ID列表", value = "用户角色id", forceRep = true)
    private List<Long> roleIds;
    @ApiModelProperty(description = "用户权限", value = "用户权限", forceRep = true)
    private List<String> permissionsList;

    public static Map<String, Field> map = new CsapMap<>();

    public List<String> getRoleList() {
        return r(roleList);
    }

    public List<Long> getRoleIds() {
        return r(roleIds);
    }

    public List<String> getPermissionsList() {
        return r(permissionsList);
    }

    private <R> List<R> r(List<R> l) {
        return Objects.isNull(l) ? Collections.emptyList() : l;
    }

    public Map<String, List<String>> getUserAttribute() {
        return userAttribute;
    }


    public boolean containsField(String name) {
        return map.containsKey(name) || userAttribute.containsKey(name);
    }

    @SneakyThrows
    public Object getValue(String field) {
        return map.containsKey(field) ? map.get(field).get(this) : String.join(",", userAttribute.get(field));
    }

    static {
        for (Field field : UserInfo.class.getDeclaredFields()) {
            map.put(field.getName(), field);
        }
    }
}
